package com.ruoyi.quartz.task;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.binding.domain.*;
import com.ruoyi.binding.domain.JDP.Params.JDPCusQueryOrderParam;
import com.ruoyi.binding.domain.JDP.Params.JDPProOrderParam;
import com.ruoyi.binding.domain.JDP.Tools.OkHttpSessionClient;
import com.ruoyi.binding.domain.MhOrderRawData;
import com.ruoyi.binding.mapper.MhOrderInfoMapper;
import com.ruoyi.binding.mapper.MhOrderRawDataMapper;
import com.ruoyi.binding.mapper.MhOrderRemoteMapper;
import com.ruoyi.binding.service.IMhUpstreamStudioConfigService;
import com.ruoyi.binding.service.impl.MhSecJDPServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
@Component
public class MhOrderSync {
    private static final Logger log = LoggerFactory.getLogger(MhOrderSync.class);

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private MhOrderRawDataMapper mhOrderRawDataMapper;
    @Autowired
    private MhOrderInfoMapper mhOrderInfoMapper;
    @Autowired
    private MhOrderRemoteMapper mhOrderRemoteMapper;

    @Autowired
    private MhSecJDPServiceImpl mhJDPService;

    @Autowired
    private IMhUpstreamStudioConfigService upstreamStudioConfigService;

    /**
     * 同步订单数据
     * 该方法会定时执行，具体的同步逻辑需要根据实际需求实现
     */
    public void syncOrders() {
        log.info("开始同步订单数据...");

        OkHttpSessionClient client = new OkHttpSessionClient();
        List<SysDept> deptList = deptService.selectAllDeptWithHttpUrl();
        log.info("共找到 {} 个部门需要同步订单数据", deptList.size());
        if (deptList.isEmpty()) {
            log.info("没有找到需要同步订单数据的部门，结束同步");
            return;
        }
        for (SysDept dept : deptList) {
            try {
                // 设置当前用户上下文
                int isLogin = mhJDPService.login(client, dept.getDeptId(), dept.getHttpUrl(), dept.getHttpUser(), dept.getHttpPwd());
                // 发请求
                if (isLogin != 1) {
                    log.error("用户 {} 登录失败，登录状态: {}", dept.getDeptName(), isLogin);
                    continue;
                }

                List<MhOrderRawData> allOrders = getAllMhOrderRawDataList(client);
                for (int index = 0; index < allOrders.size(); index++) {
                    allOrders.get(index).setDeptId(Long.valueOf(client.getCurrentUser().getDeptId()));
                    mhOrderInfoMapper.insertMhOrderInfo(convertToMhOrderInfo(allOrders.get(index)));
                    mhOrderRawDataMapper.insertMhOrderRawData(allOrders.get(index));

                }
                log.info("用户 {} 同步订单数据完成，共同步 {} 条订单", dept.getDeptName(), allOrders.size());

            } catch (Exception e) {
                log.error("用户登录失败",e);
            } finally {
                client.clearCurrentUser(); // 清除当前用户上下文
            }
        }
    }


    // 建议：如果你的项目已有事务管理，这里可以加 @Transactional(rollbackFor = Exception.class)
    public void syncUpStreamOrders() {
        final long jobStart = System.currentTimeMillis();
        log.info("====== [UpstreamSync] 开始同步上家大厅数据 ======");

        OkHttpSessionClient client = new OkHttpSessionClient();

        List<MhUpstreamStudioConfig> upstreamConfigs =
                upstreamStudioConfigService.selectMhUpstreamStudioConfigNoScopeList(new MhUpstreamStudioConfig());
        log.info("[UpstreamSync] 发现上家大厅配置数量: {}", upstreamConfigs.size());

        if (upstreamConfigs.isEmpty()) {
            log.info("[UpstreamSync] 无上家配置，任务结束。耗时 {} ms", cost(jobStart));
            return;
        }

        // 统计指标
        int loginSuccess = 0;
        int loginFailed  = 0;
        int totalFetchedBeforeDedup = 0;

        // 汇总：所有远程订单（含重复）
        List<MhOrderRemote> allRemoteOrders = new ArrayList<>();
        // 汇总：所有远程订单ID（去重）
        Set<String> allRemoteOrderIds = new LinkedHashSet<>();

        // 记录各上家抓取数量
        Map<Long, Integer> deptFetchCount = new LinkedHashMap<>();

        for (MhUpstreamStudioConfig config : upstreamConfigs) {
            final long oneStart = System.currentTimeMillis();
            Long deptId = config.getDeptId();

            try {
                log.info("[UpstreamSync][{}|{}] 准备登录上家: url={}, user={}",
                        deptId, nz(config.getStudioName()), nz(config.getStudioUrl()), nz(config.getUsername()));
                final long loginStart = System.currentTimeMillis();
                int isLogin = mhJDPService.login(client, deptId, config.getStudioUrl(), config.getUsername(), config.getPassword());
                log.info("[UpstreamSync][{}|{}] 登录结果: {} (耗时 {} ms)",
                        deptId, nz(config.getStudioName()), isLogin, cost(loginStart));

                if (isLogin != 1) {
                    loginFailed++;
                    log.warn("[UpstreamSync][{}|{}] 登录失败，跳过该上家。", deptId, nz(config.getStudioName()));
                    continue;
                }
                loginSuccess++;

                // 拉取数据
                final long fetchStart = System.currentTimeMillis();
                List<MhOrderRemote> remoteOrders = getSingleRemoteOrders(client);
                if (remoteOrders == null) remoteOrders = Collections.emptyList();

                // 标注 deptId（不参与删除逻辑，仅保留来源信息）
                for (MhOrderRemote order : remoteOrders) {
                    order.setDeptId(deptId);
                }

                totalFetchedBeforeDedup += remoteOrders.size();
                deptFetchCount.put(deptId, remoteOrders.size());
                log.info("[UpstreamSync][{}|{}] 拉取远程订单 {} 条 (耗时 {} ms)。样本: {}",
                        deptId, nz(config.getStudioName()), remoteOrders.size(), cost(fetchStart),
                        previewIds(remoteOrders.stream().map(MhOrderRemote::getOrderId).filter(Objects::nonNull).collect(Collectors.toList()), 20));

                // 累积
                allRemoteOrders.addAll(remoteOrders);
                for (MhOrderRemote order : remoteOrders) {
                    if (order.getOrderId() != null) {
                        allRemoteOrderIds.add(order.getOrderId());
                    }
                }

                log.info("[UpstreamSync][{}|{}] 本轮合并后累计：订单条数(含重复)={}, 唯一orderId数={}. 本上家耗时 {} ms",
                        deptId, nz(config.getStudioName()), allRemoteOrders.size(), allRemoteOrderIds.size(), cost(oneStart));

            } catch (Exception e) {
                loginFailed++;
                log.error("[UpstreamSync][{}|{}] 同步异常：{}", config.getDeptId(), nz(config.getStudioName()), e.getMessage(), e);
            } finally {
                client.clearCurrentUser(); // 不同上家间清理会话
            }
        }

        log.info("[UpstreamSync] 登录成功 {}/{}，登录失败 {}。累计抓取(含重复) {} 条，唯一 orderId {} 个。",
                loginSuccess, upstreamConfigs.size(), loginFailed, totalFetchedBeforeDedup, allRemoteOrderIds.size());

        // 去重（按 orderId 保留“最后一次出现”的记录）
        final long dedupStart = System.currentTimeMillis();
        Map<String, MhOrderRemote> lastWinMap = new LinkedHashMap<>();
        for (MhOrderRemote o : allRemoteOrders) {
            if (o.getOrderId() != null) {
                lastWinMap.put(o.getOrderId(), o); // 相同 orderId 以最后一次为准
            }
        }
        List<MhOrderRemote> merged = new ArrayList<>(lastWinMap.values());
        int dupCount = totalFetchedBeforeDedup - merged.size();
        log.info("[UpstreamSync] 去重完成：去除重复 {} 条，保留 {} 条 (unique)。耗时 {} ms。样本 orderId: {}",
                dupCount, merged.size(), cost(dedupStart), previewIds(lastWinMap.keySet(), 30));

        // ====== 循环后统一写库 & 统一删除 ======
        if (!merged.isEmpty()) {
            // 1) 批量插入或更新
            final long upsertStart = System.currentTimeMillis();
            int affect = 0;
            try {
                affect = mhOrderRemoteMapper.insertOrUpdateMhOrderRemoteList(merged);
            } catch (Exception e) {
                log.error("[UpstreamSync] 批量插入/更新异常：{}", e.getMessage(), e);
                // 这里可按需决定是否 return/抛出异常
            }
            log.info("[UpstreamSync] 批量插入/更新完成：尝试写入 {} 条，Mapper返回影响行数={}。耗时 {} ms。",
                    merged.size(), affect, cost(upsertStart));

            // 2) 统一删除（核心：基于“全局 orderId 白名单”）
            // 由于不新增XML，这里沿用现有 deleteByDeptIdNotInOrderIds(deptId, orderIds)
            // 实现方式：对所有已知 deptId 逐个调用，但传入同一份全局 orderIds —— 结果上等价于“只按 orderId 保留”，不受部门维度影响。
            final List<String> globalIds = new ArrayList<>(lastWinMap.keySet());
            final long deleteStart = System.currentTimeMillis();
            int deptDeleteCalls = 0;

            for (MhUpstreamStudioConfig cfg : upstreamConfigs) {
                Long deptId = cfg.getDeptId();
                Map<String, Object> params = new HashMap<>();
                params.put("deptId", deptId);          // 方法签名要求；不新增XML的前提下仍需传
                params.put("orderIds", globalIds);     // 核心白名单（全局同一份）

                final long oneDeleteStart = System.currentTimeMillis();
                try {
                    mhOrderRemoteMapper.deleteByDeptIdNotInOrderIds(params);
                    deptDeleteCalls++;
                    log.info("[UpstreamSync][删除] deptId={} 已执行基于全局orderId白名单的清理。保留ID数={}，样本: {}。耗时 {} ms。",
                            deptId, globalIds.size(), previewIds(globalIds, 20), cost(oneDeleteStart));
                } catch (Exception e) {
                    log.error("[UpstreamSync][删除] deptId={} 清理异常：{}", deptId, e.getMessage(), e);
                }
            }
            log.info("[UpstreamSync] 全局删除完成：对 {} 个部门执行了基于全局 orderId 白名单的清理。耗时 {} ms。",
                    deptDeleteCalls, cost(deleteStart));

        } else {
            // merged 为空：所有上家本次都没有订单 -> 清空所有部门的数据（沿用已有 deleteByDeptId）
            final long clearStart = System.currentTimeMillis();
            int cleared = 0;
            for (MhUpstreamStudioConfig cfg : upstreamConfigs) {
                try {
                    mhOrderRemoteMapper.deleteByDeptId(cfg.getDeptId());
                    cleared++;
                    log.info("[UpstreamSync][清空] deptId={} 已清空（本次未抓取到任何订单）。", cfg.getDeptId());
                } catch (Exception e) {
                    log.error("[UpstreamSync][清空] deptId={} 清空异常：{}", cfg.getDeptId(), e.getMessage(), e);
                }
            }
            log.info("[UpstreamSync] 所有上家均无订单，已按部门清空 {} 个。耗时 {} ms。", cleared, cost(clearStart));
        }

        // 汇总日志
        log.info("====== [UpstreamSync] 同步完成：登录成功 {}, 失败 {}；抓取(含重复) {} 条；唯一 {} 条；总耗时 {} ms ======",
                loginSuccess, loginFailed, totalFetchedBeforeDedup, allRemoteOrderIds.size(), cost(jobStart));
    }

    /** 工具方法：耗时 */
    private static long cost(long startMs) {
        return System.currentTimeMillis() - startMs;
    }

    /** 工具方法：null 转安全字符串 */
    private static String nz(Object o) {
        return o == null ? "" : String.valueOf(o);
    }

    /** 工具方法：预览若干 ID，避免日志过长 */
    private static String previewIds(Collection<String> ids, int limit) {
        if (ids == null || ids.isEmpty()) return "[]";
        StringBuilder sb = new StringBuilder("[");
        int i = 0;
        for (String id : ids) {
            if (i++ >= limit) {
                sb.append("... total=").append(ids.size());
                break;
            }
            if (sb.length() > 1) sb.append(", ");
            sb.append(id);
        }
        if (sb.charAt(sb.length()-1) != ']') sb.append(']');
        return sb.toString();
    }



    private List<String> getGameType(OkHttpSessionClient client) throws Exception {
        List<String> resultList = new ArrayList<>();
        JSONArray gameTypeResult = mhJDPService.queryGameType(client).getJSONArray("data");
        for (int i = 0; i < gameTypeResult.size(); i++) {
            JSONObject jsonObject = gameTypeResult.getJSONObject(i);
            resultList.add(jsonObject.getString("gameName"));
        }
        return resultList;
    }

    public List<MhOrderRemote> getSingleRemoteOrders(OkHttpSessionClient client) throws Exception {
         //获取所有游戏类型
//        List<String> gameTypeList = getGameType(client);


        String[] gameTypeList = {"三角洲行动", "鸣潮", "原神"};


        List<MhOrderRemote> allOrders = new ArrayList<>();
        for (String gameType : gameTypeList) {

            List<MhOrderRemote> gameOrderList = new ArrayList<>();
            JDPProOrderParam param = new JDPProOrderParam();
            param.setGameName(gameType);
            JSONObject curGameOrders = mhJDPService.queryInsideRecOrder(client, param);
            log.info("返回结果: {}", curGameOrders);
            JSONArray dataArray = curGameOrders.getJSONArray("data");
            if (dataArray == null || dataArray.isEmpty()) {
                log.info("{} 无订单数据，跳过", gameType);
                continue;
            }
            for (int i = 0; i < dataArray.size(); i++) {
                // 解析每个订单数据
                JSONObject orderJson = dataArray.getJSONObject(i);
                MhOrderRemote order = new MhOrderRemote();
                order.setGameName(orderJson.getString("gameName"));
                order.setOrderId(orderJson.getString("orderId"));
                order.setOrderIdView(orderJson.getString("orderIdView"));
                order.setProject(orderJson.getString("project"));
                order.setRecFee(orderJson.getBigDecimal("recFee"));
                order.setOrderRemark(orderJson.getString("orderRemark"));
                order.setOrderSta(orderJson.getString("orderSta"));
                order.setDeptId(Long.valueOf(client.getCurrentUser().getDeptId()));
                order.setAssUserName(client.getCurrentUser().getBaseUrl());
                gameOrderList.add(order);
            }
            allOrders.addAll(gameOrderList);
            log.info("{} 同步订单数据完成，共 {} 条订单", gameType, gameOrderList.size());
            // 避免请求过快导致上家服务器拒绝连接
            Thread.sleep(2000); // 等待2秒
        }
        return allOrders;
    }

    public List<MhOrderRawData> getAllMhOrderRawDataList(OkHttpSessionClient client) throws Exception {
        // 获取所有游戏类型
        List<String> gameTypeList = getGameType(client);
        final int pageSize = 100;

        List<MhOrderRawData> allOrders = new ArrayList<>();

        for (String gameType : gameTypeList) {
            List<MhOrderRawData> gameOrderList = new ArrayList<>();
            JDPCusQueryOrderParam param = new JDPCusQueryOrderParam();
            param.setGameName(gameType);
            param.setPage(1);

            JSONObject firstPageResult = mhJDPService.queryOrder(client, param);
            if (firstPageResult.getIntValue("code") != 0) {
                log.info("{} 第1页获取失败，跳过该游戏类型", gameType);
                continue;
            }

            JSONArray firstPageData = firstPageResult.getJSONArray("data");
            if (firstPageData == null || firstPageData.isEmpty()) {
                log.info("{} 第1页无数据，结束查询", gameType);
                continue;
            }

            for (int i = 0; i < firstPageData.size(); i++) {
                MhOrderRawData order = convertJsonToMhOrderRawData(firstPageData.getJSONObject(i));
                gameOrderList.add(order);
            }

            // 从total里取总订单数
            int totalCount = 0;
            JSONObject totalObj = firstPageResult.getJSONObject("total");
            if (totalObj != null) {
                totalCount = totalObj.getIntValue("TotalCount");
            }
            int totalPages = totalCount > 0 ? (totalCount + pageSize - 1) / pageSize : 1;

            if (totalPages <= 1) {
                log.info("{} 只有1页数据，查询结束，订单数：{}", gameType, gameOrderList.size());
                allOrders.addAll(gameOrderList);
                continue;
            }

            // 串行查询剩余页
            for (int page = 2; page <= totalPages; page++) {
                JDPCusQueryOrderParam p = new JDPCusQueryOrderParam();
                p.setGameName(gameType);
                p.setPage(page);

                JSONObject pageResult = mhJDPService.queryOrder(client, p);

                if (pageResult.getIntValue("code") == 0) {
                    JSONArray data = pageResult.getJSONArray("data");
                    if (data != null && !data.isEmpty()) {
                        for (int i = 0; i < data.size(); i++) {
                            gameOrderList.add(convertJsonToMhOrderRawData(data.getJSONObject(i)));
                        }
                        log.info("{} 第{}页 获取 {} 条订单", gameType, page, data.size());
                    } else {
                        log.info("{} 第{}页 无订单数据", gameType, page);
                    }
                } else {
                    log.info("{} 第{}页 获取失败", gameType, page);
                }
            }

            log.info("{} 总共获取订单数：{}", gameType, gameOrderList.size());
            allOrders.addAll(gameOrderList);
        }

        return allOrders;
    }


    /**
     * 查询数据汇总列表
     */
    private MhOrderRawData convertJsonToMhOrderRawData(JSONObject jsonObject) {
        MhOrderRawData rawData = new MhOrderRawData();

        rawData.setOid(jsonObject.getLong("oid"));
        rawData.setOrderId(jsonObject.getString("orderId"));
        rawData.setOrderIdView(jsonObject.getString("orderIdView"));
        rawData.setGameName(jsonObject.getString("gameName"));
        rawData.setGameArea(jsonObject.getString("gameArea"));
        rawData.setGameServer(jsonObject.getString("gameServer"));
        rawData.setGameJob(jsonObject.getString("gameJob"));
        rawData.setGameGroup(jsonObject.getString("gameGroup"));
        rawData.setRoleName(jsonObject.getString("roleName"));
        rawData.setLevelMark(jsonObject.getString("levelMark"));
        //    rawData.setItemRemark(jsonObject.getString("itemRemark"));
        //    rawData.setOtherRemark(jsonObject.getString("otherRemark"));
        //   rawData.setOrderLabel(jsonObject.getString("orderLabel"));
        //   rawData.setOrderLabelColor(jsonObject.getString("orderLabelColor"));
        rawData.setHours(jsonObject.getBigDecimal("hours"));
        rawData.setOrderHoursDescStr(jsonObject.getString("orderHoursDescStr"));
        rawData.setOrderSta(jsonObject.getString("orderSta"));
        rawData.setProject(jsonObject.getString("project"));
        rawData.setAssTime(jsonObject.getDate("assTime"));
        rawData.setStartTime(jsonObject.getDate("startTime"));
        rawData.setExpectEndTime(jsonObject.getString("expectEndTime"));
        if(jsonObject.getString("recManName") == null || jsonObject.getString("recManName").isEmpty()) {
            rawData.setRecManName("未指派");
        } else {
            rawData.setRecManName(jsonObject.getString("recManName"));
        }
        rawData.setRecFee(jsonObject.getBigDecimal("recFee"));
        rawData.setIsAutoAssignment(jsonObject.getString("isAutoAssignment"));
        //    rawData.setAutoAssignmentManName(jsonObject.getString("autoAssignmentManName"));
        //    rawData.setRecOrderTime(jsonObject.getDate("recOrderTime"));
        rawData.setJiwei(jsonObject.getString("jiwei"));
        rawData.setIsRead(jsonObject.getString("isRead"));
        rawData.setIsJiaJi(jsonObject.getString("isJiaJi"));
        rawData.setIsSplitOrder(jsonObject.getString("isSplitOrder"));
        rawData.setCustomizeTag(jsonObject.getString("customizeTag"));
        rawData.setDynamicRemark(jsonObject.getString("dynamicRemark"));
        rawData.setOrderRemark(jsonObject.getString("orderRemark"));
        //    rawData.setTaskId(jsonObject.getLong("taskId"));
        //    rawData.setTaskName(jsonObject.getString("taskName"));
        //    rawData.setGameAcc(jsonObject.getString("gameAcc"));
        //    rawData.setAccPwd(jsonObject.getString("accPwd"));
        rawData.setZgameAcc(jsonObject.getString("zgameAcc"));
        rawData.setOrderContent(jsonObject.getString("orderContent"));
        rawData.setBackListId(jsonObject.getLong("backListId"));
        //    rawData.setSplitId(jsonObject.getLong("splitId"));
        //    rawData.setMoblie(jsonObject.getString("moblie"));
        //     rawData.setQq(jsonObject.getString("qq"));
        //    rawData.setWangWang(jsonObject.getString("WangWang"));
        rawData.setOrderSoure(jsonObject.getString("orderSoure"));
        //    rawData.setSoureFromHost(jsonObject.getString("soureFromHost"));
        rawData.setPrice(jsonObject.getBigDecimal("price"));
        rawData.setInputOrderManName(jsonObject.getString("inputOrderManName"));
        rawData.setAssUserName(jsonObject.getString("assUserName"));
        rawData.setIsThrowOrder(jsonObject.getString("isThrowOrder"));
        rawData.setIsSettStatus(jsonObject.getString("isSettStatus"));
        //    rawData.setOrderFromOrderId(jsonObject.getString("orderFromOrderId"));
        rawData.setIsAllowChangeOrderFee(jsonObject.getString("isAllowChangeOrderFee"));
        rawData.setRecOrderInsureAmount(jsonObject.getBigDecimal("recOrderInsureAmount"));
        rawData.setPayMethod(jsonObject.getLong("payMethod"));
        //    rawData.setServiceAmount(jsonObject.getBigDecimal("serviceAmount"));
        rawData.setIsPushJdp(jsonObject.getString("isPushJdp"));
        rawData.setThrowCount(jsonObject.getLong("throwCount"));
        rawData.setTransfType(jsonObject.getLong("transfType"));
        //    rawData.setPushJdpOrderState(jsonObject.getString("pushJdpOrderState"));
        rawData.setCompleteTime(parseDate(jsonObject.getString("completeTime")));
        rawData.setGroupMangeUid(jsonObject.getLong("groupMangeUid"));
        rawData.setRecSettCount(jsonObject.getLong("recSettCount"));
        rawData.setImgCount(jsonObject.getLong("imgCount"));
        //    rawData.setSphone(jsonObject.getString("sphone"));
        //    rawData.setDelTime(jsonObject.getDate("delTime"));
        //    rawData.setDelUserName(jsonObject.getString("delUserName"));
        rawData.setBussType(jsonObject.getLong("bussType"));
        rawData.setAddOrderUserName(jsonObject.getString("addOrderUserName"));
        //    rawData.setRefundFee(jsonObject.getBigDecimal("refundFee"));
        //    rawData.setRefundTimeStr(jsonObject.getString("refundTimeStr"));
        //   rawData.setRefundModel(jsonObject.getString("refundModel"));
        //   rawData.setRefundUserName(jsonObject.getString("refundUserName"));
        //   rawData.setProjectTypeName(jsonObject.getString("projectTypeName"));
        //   rawData.setNetReceipts(jsonObject.getString("netReceipts"));
        //   rawData.setTid(jsonObject.getString("tid"));
        //    rawData.setFsid(jsonObject.getLong("fsid"));
        //   rawData.setCustomerId(jsonObject.getLong("customerId"));
        rawData.setOriginPrice(jsonObject.getBigDecimal("originPrice"));
        rawData.setDiscount(jsonObject.getBigDecimal("discount"));

        return rawData;
    }

    private Date parseDate(Object obj) {
        if (obj == null) return null;
        String s = obj.toString();
        if (s.startsWith("/Date(") && s.endsWith(")/")) {
            long timestamp = Long.parseLong(s.replaceAll("[^0-9]", ""));
            return new Date(timestamp);
        }
        return null;
    }

    private MhOrderInfo convertToMhOrderInfo(MhOrderRawData rawData) {
        MhOrderInfo mhOrderInfo = new MhOrderInfo();
        mhOrderInfo.setOrderId(rawData.getOrderId());
        mhOrderInfo.setOrderIdView(rawData.getOrderIdView());
        mhOrderInfo.setGameName(rawData.getGameName());
        mhOrderInfo.setProject(rawData.getProject());
        mhOrderInfo.setPrice(rawData.getPrice());
        mhOrderInfo.setRecManName(rawData.getRecManName());
        mhOrderInfo.setRecFee(rawData.getRecFee());
        mhOrderInfo.setOrderSta(rawData.getOrderSta());
        mhOrderInfo.setIsSettStatus(rawData.getIsSettStatus());
        mhOrderInfo.setAssUserName(rawData.getAssUserName());
        mhOrderInfo.setAssTime(rawData.getAssTime());
        mhOrderInfo.setJiwei(rawData.getJiwei());
        mhOrderInfo.setOrderRemark(rawData.getOrderRemark());
        mhOrderInfo.setDeptId(rawData.getDeptId());
        return mhOrderInfo;
    }

}
